import { HttpException, Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { User } from './entities/user.entity'
import { Repository } from 'typeorm'
import { InjectRepository } from '@nestjs/typeorm';


@Injectable()
export class UserService {
  // 依赖注入：把用户实体注入到userRepository中，这样该变量就可以操作用户实体，进而同步到数据库
  constructor(
    @InjectRepository(User)
    private userRepository: Repository<User>
  ) { }
  //登录
  async login(params: CreateUserDto) {
    // console.log(params);
    //取出请求传过来的用户名和密码，从数据库中查询数据，能查到就代表登录成功，否则用户名，密码错误
    const { username, password} = params
    const res = await this.userRepository.findOne({
      where:{
        username,
        password
      },
      //查询的内容
      select:['id','username']
    })
    if(!res){
      throw new HttpException('用户名或密码错误',200)
    }
    // console.log(res);
    
    return res

  }

  //添加用户
  async create(createUserDto: CreateUserDto) {
    // return 'This action adds a new user';
    return await this.userRepository.save(createUserDto)
  }

  async findAll() {
    // return `This action returns all user`;
    return await this.userRepository.find();
  }

  findOne(id: number) {
    return `This action returns a #${id} user`;
  }

  update(id: number, updateUserDto: UpdateUserDto) {
    return `This action updates a #${id} user`;
  }

  remove(id: number) {
    return `This action removes a #${id} user`;
  }
}
